#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using TVC.Modules.CustomControl;

#endregion

namespace TVC.Modules.Business
{
    public partial class InvoiceSplit : Form
    {
        public string type;
        public List<string> contractChanged = new List<string>();
        public InvoiceSplit()
        {
            InitializeComponent();
            initSplit();
        }

        public MainForm MainForm { get; set; }
        public DTO.InvoiceRegisterInfo Invoice { get; set; }
        public InvoiceSplit(MainForm frm, DTO.InvoiceRegisterInfo inf)
        {
            InitializeComponent();
            MainForm = frm;
            Invoice = inf;
            initSplit();

        }
        DataTable _dtBudget = null;
        DataTable _dtContract = null;
        DataTable _dtEmployee = null;
        private void AddItem(decimal amount, decimal otherAmt, string dept, string budget, string contract, string emp, string desc, string key = "-1")
        {
            ListViewItem objItem = new ListViewItem();

            NumericUpDown amt = new NumericUpDown();
            amt.Minimum = txtAmount.Minimum;
            amt.Maximum = txtAmount.Maximum;
            amt.DecimalPlaces = txtAmount.DecimalPlaces;
            amt.Value = amount;
            amt.ThousandsSeparator = txtAmount.ThousandsSeparator;
            amt.Name = "Amount";
            amt.Tag = objItem;
            objItem.SubItems.Add(amt);
            //amt.Enter += new EventHandler(amt_Enter);

            NumericUpDown oamt = new NumericUpDown();
            oamt.Minimum = txtAmount.Minimum;
            oamt.Maximum = txtAmount.Maximum;
            oamt.DecimalPlaces = txtAmount.DecimalPlaces;
            oamt.Value = otherAmt;
            oamt.ThousandsSeparator = txtAmount.ThousandsSeparator;
            oamt.Name = "OtherAmt";
            oamt.Tag = objItem;
            objItem.SubItems.Add(oamt);
            //oamt.Enter += new EventHandler(amt_Enter);

            TextBox txDept = new TextBox();
            txDept.Text = dept;
            txDept.Name = "Department";
            txDept.Tag = objItem;
            objItem.SubItems.Add(txDept);

            CustomControl.LookupBox lkBudget = new CustomControl.LookupBox();
            lkBudget.DisplayMember = "BudgetCode";
            lkBudget.ValueMember = "BudgetCode";
            lkBudget.MainForm = MainForm;
            lkBudget.Lookup = "bgC";

            lkBudget.DataSource = _dtBudget;
            lkBudget.Value = Invoice.Budget;
            lkBudget.Name = "Budget";
            lkBudget.Tag = objItem;
            objItem.SubItems.Add(lkBudget);

            CustomControl.LookupBox lkContract = new CustomControl.LookupBox();
            lkContract.DisplayMember = "Contract";
            lkContract.ValueMember = "Contract";
            lkContract.MainForm = MainForm;
            lkContract.Lookup = "cboCTPO";

            lkContract.DataSource = _dtContract;
            lkContract.Value = Invoice.Contract;
            lkContract.Name = "Contract";
            lkContract.Tag = objItem;
            objItem.SubItems.Add(lkContract);

            CustomControl.LookupBox lkEmployee = new CustomControl.LookupBox();
            lkEmployee.DisplayMember = "EmployeeCode";
            lkEmployee.ValueMember = "EmployeeCode";
            lkEmployee.MainForm = MainForm;
            lkEmployee.Lookup = "Employee";
            lkEmployee.Name = "Employee";
            lkEmployee.DataSource = _dtEmployee;
            lkEmployee.Value = Invoice.Employee;
            lkEmployee.Tag = objItem;
            objItem.SubItems.Add(lkEmployee);

            TextBox txDescription = new TextBox();
            txDescription.Text = Invoice.Description;
            txDescription.Name = "Description";
            txDescription.Tag = objItem;
            objItem.SubItems.Add(txDescription);


            lvSplit.Items.Add(objItem);
        }

        //void amt_Enter(object sender, EventArgs e)
        //{
        //    (sender as NumericUpDown).Select(0, (sender as NumericUpDown).ToString().Length);
        //}
        private void initSplit()
        {
            string sErr = "";
            txtAmount.Value = Convert.ToDecimal(Invoice.Amt);
            txtOAmount.Value = Convert.ToDecimal(Invoice.OtherAmt);
            BUS.BudgetsControl ctrcontr = new BUS.BudgetsControl();
            if (MainForm.PODInfo.Business_ID == "HL") _dtBudget = ctrcontr.GetAll_Budgets(ref sErr);
            else _dtBudget = ctrcontr.GetAll_Budgets1(ref sErr);

            BUS.ContractControl ctrCT = new BUS.ContractControl();
            if (MainForm.PODInfo.Business_ID == "HL") _dtContract = ctrCT.GetAll_Contract(ref sErr);
            else _dtContract = ctrCT.GetAll_Contract1(ref sErr);

            BUS.EmployeeControl ctrEMP = new BUS.EmployeeControl();
            _dtEmployee = ctrEMP.GetAll_Employee(ref sErr);

            AddItem(txtAmount.Value, txtOAmount.Value, Invoice.Department, Invoice.Budget, Invoice.Contract, Invoice.Employee, Invoice.Description, Invoice.LineNo.ToString());
            contractChanged.Add(Invoice.Contract);

        }


        private void btSplit_Click(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (lvSplit.CheckedItems.Count > 0)
            {
                for (int i = 0; i < lvSplit.CheckedItems.Count; i++)
                {
                    ListViewItem objItem = lvSplit.CheckedItems[i] as ListViewItem;
                    decimal newVal = nfPercent.Value;
                    decimal val = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value - newVal;

                    ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value = val;

                    decimal newOVal = (newVal / txtAmount.Value) * txtOAmount.Value;
                    decimal oval = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value - newOVal;
                    ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value = oval;
                    decimal difVal = 0, difOVal = 0;
                    foreach (ListViewItem item in lvSplit.Items)
                    {
                        if (item.Index == objItem.Index)
                        {
                            difVal += newVal;
                            difOVal += newOVal;
                        }
                        else
                        {
                            difVal += ((NumericUpDown)((ListViewItem.ListViewSubControlItem)item.SubItems[0]).Control).Value;
                            difOVal += ((NumericUpDown)((ListViewItem.ListViewSubControlItem)item.SubItems[1]).Control).Value;
                        }


                    }

                    if (val + difVal != txtAmount.Value)
                    {
                        ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value = val = txtAmount.Value - difVal;
                    }
                    if (oval + difOVal != txtOAmount.Value)
                    {
                        ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value = oval = txtOAmount.Value - difOVal;
                    }
                    //((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value = val;
                    //((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value = oval;
                    AddItem(newVal, newOVal, Invoice.Department, Invoice.Budget, Invoice.Contract, Invoice.Employee, Invoice.Description);
                }
            }
        }

        private void btRemove_Click(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (lvSplit.CheckedItems.Count > 0)
            {
                for (int i = 0; i < lvSplit.CheckedItems.Count; i++)
                {
                    ListViewItem objItem = lvSplit.CheckedItems[i] as ListViewItem;
                    if (objItem.Index != 0)
                    {
                        decimal val = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value;
                        decimal oval = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value;
                        ListViewItem preItem = lvSplit.Items[objItem.Index - 1];
                        ListViewItem.ListViewSubControlItem preSubItem = preItem.SubItems[0] as ListViewItem.ListViewSubControlItem;
                        ((NumericUpDown)preSubItem.Control).Value = ((NumericUpDown)preSubItem.Control).Value + val;
                        ListViewItem.ListViewSubControlItem preOSubItem = preItem.SubItems[1] as ListViewItem.ListViewSubControlItem;
                        ((NumericUpDown)preOSubItem.Control).Value = ((NumericUpDown)preOSubItem.Control).Value + oval;
                        lvSplit.Items.Remove(objItem);
                    }
                }

            }
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btOk_Click(object sender, EventArgs e)
        {
            string sErr = "";

            if (lvSplit.Items.Count > 1)
            {
                BUS.InvoiceRegisterControl ctr = new BUS.InvoiceRegisterControl();

                List<DTO.InvoiceRegisterInfo> listInf = new List<DTO.InvoiceRegisterInfo>();
                double total = 0;
                decimal totalOther = 0;
                double vat = 0;
                double vatOther = 0;
                double payment = 0;
                double payother = 0;
                double expense = 0;
                double cit = 0;
                for (int i = 0; i < lvSplit.Items.Count; i++)
                {
                    ListViewItem item = lvSplit.Items[i];
                    DTO.InvoiceRegisterInfo it = new DTO.InvoiceRegisterInfo(Invoice);

                    it.Amt = Convert.ToDouble(((NumericUpDown)((ListViewItem.ListViewSubControlItem)item.SubItems[0]).Control).Value);
                    it.Department = ((TextBox)((ListViewItem.ListViewSubControlItem)item.SubItems[2]).Control).Text;
                    it.Budget = ((LookupBox)((ListViewItem.ListViewSubControlItem)item.SubItems[3]).Control).Value.ToString();
                    it.Contract = ((LookupBox)((ListViewItem.ListViewSubControlItem)item.SubItems[4]).Control).Value.ToString();
                    it.Employee = ((LookupBox)((ListViewItem.ListViewSubControlItem)item.SubItems[5]).Control).Value.ToString();
                    it.Description = ((TextBox)((ListViewItem.ListViewSubControlItem)item.SubItems[6]).Control).Text;

                    double factor = it.Amt / Invoice.Amt;
                    it.OtherAmt = Math.Round(Invoice.OtherAmt * factor, 2);
                    it.VAT = Math.Round(Invoice.VAT * factor, 2);
                    it.VATOther = Math.Round(Invoice.VATOther * factor, 2);
                    it.PayableAmt = Math.Round(Invoice.PayableAmt * factor, 2);
                    it.PayableAmtOther = Math.Round(Invoice.PayableAmtOther * factor, 2);
                    it.ExpenseAmt = Math.Round(Invoice.ExpenseAmt * factor, 2);
                    it.CIT = Math.Round(Invoice.CIT * factor, 2);

                    if (i == lvSplit.Items.Count - 1)
                    {
                        it.OtherAmt = Invoice.OtherAmt - Convert.ToDouble(totalOther);
                        it.VAT = Invoice.VAT - vat;
                        it.VATOther = Invoice.VATOther - vatOther;
                        it.PayableAmt = Invoice.PayableAmt - payment;
                        it.PayableAmtOther = Invoice.PayableAmtOther - payother;
                        it.ExpenseAmt = Invoice.ExpenseAmt - expense;
                        it.CIT = Invoice.CIT - cit;
                    }

                    vat += it.VAT;
                    vatOther += it.VATOther;
                    payment += it.PayableAmt;
                    payother += it.PayableAmtOther;
                    expense += it.ExpenseAmt;
                    total += it.Amt;
                    totalOther += Convert.ToDecimal(it.OtherAmt);
                    cit += it.CIT;

                    listInf.Add(it);
                }

                if (Math.Round(total, txtAmount.DecimalPlaces) != Math.Round(Convert.ToDouble(txtAmount.Value), txtAmount.DecimalPlaces)) sErr = "Total Amount is not balance";

                if (sErr == "")
                {
                    int maxLine = ctr.getMaxLineNo(MainForm.PODInfo.Business_ID, Invoice.Reference, ref sErr);
                    if (maxLine == 0) maxLine = 10000;
                    ctr.BeginTransaction(ref sErr);
                    for (int i = 0; i < listInf.Count; i++)
                    {
                        if (sErr != "") break;
                        DTO.InvoiceRegisterInfo itemInf = listInf[i];
                        if (i == 0)
                        {
                            if (MainForm.PODInfo.Business_ID == "HL") sErr = ctr.Update_InvoiceRegister(itemInf);
                            else sErr = ctr.Update_InvoiceRegister1(itemInf);
                        }
                        else
                        {
                            itemInf.LineNo = Convert.ToInt16(maxLine - 1);
                            maxLine--;
                            if (MainForm.PODInfo.Business_ID == "HL") ctr.Add_InvoiceRegister(itemInf, ref sErr);
                            else ctr.Add_InvoiceRegister1(itemInf, ref sErr);
                        }
                        if (!contractChanged.Contains(itemInf.Contract)) contractChanged.Add(itemInf.Contract);

                    }

                    if (sErr != "")
                    {
                        ctr.RollbackTransaction(ref sErr);
                        MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                    }
                    else
                    {
                        ctr.CommitTransaction(ref sErr);
                        MessageBox.Show("Amount is splited successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                        DialogResult = Gizmox.WebGUI.Forms.DialogResult.OK;
                        Close();
                    }

                }
                else
                {
                    MessageBox.Show(sErr, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error, false);
                }
            }
        }

        private void btOSplit_Click(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });
            if (lvSplit.CheckedItems.Count > 0)
            {
                for (int i = 0; i < lvSplit.CheckedItems.Count; i++)
                {
                    ListViewItem objItem = lvSplit.CheckedItems[i] as ListViewItem;
                    decimal newVal = nfOPercent.Value;
                    decimal val = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value - newVal;

                    ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value = val;

                    decimal newOVal = (newVal / txtOAmount.Value) * txtAmount.Value;
                    decimal oval = ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value - newOVal;
                    ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value = oval;
                    decimal difVal = 0, difOVal = 0;
                    foreach (ListViewItem item in lvSplit.Items)
                    {
                        if (item.Index == objItem.Index)
                        {
                            difVal += newVal;
                            difOVal += newOVal;
                        }
                        else
                        {
                            difVal += ((NumericUpDown)((ListViewItem.ListViewSubControlItem)item.SubItems[1]).Control).Value;
                            difOVal += ((NumericUpDown)((ListViewItem.ListViewSubControlItem)item.SubItems[0]).Control).Value;
                        }


                    }

                    if (val + difVal != txtOAmount.Value)
                    {
                        ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[1]).Control).Value = val = txtAmount.Value - difVal;
                    }
                    if (oval + difOVal != txtAmount.Value)
                    {
                        ((NumericUpDown)((ListViewItem.ListViewSubControlItem)objItem.SubItems[0]).Control).Value = oval = txtOAmount.Value - difOVal;
                    }


                    AddItem(newOVal, newVal, Invoice.Department, Invoice.Budget, Invoice.Contract, Invoice.Employee, Invoice.Description);
                }
            }
        }

        private void InvoiceSplit_Load(object sender, EventArgs e)
        {
            VWGClientContext.Current.Invoke("tvcNumbericFocus", new object[] { });

        }
    }
}